package com.acwing.partition2;

import java.io.*;
import java.util.LinkedList;

/**
 * @author `RKC`
 * @date 2021/12/26 16:11
 */
public class AC188武士风度的牛 {

    private static final int R = 155, C = 155;
    private static int r = 0, c = 0;
    private static final char[][] graph = new char[R][C];
    private static final int[][] dis = new int[R][C];

    private static final int[][] dirs = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}};

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        String[] s = reader.readLine().split("\\s+");
        c = Integer.parseInt(s[0]);
        r = Integer.parseInt(s[1]);
        for (int i = 0; i < r; i++) {
            String str = reader.readLine();
            for (int j = 0; j < c; j++) graph[i][j] = str.charAt(j);
        }
        writer.write(String.valueOf(bfs()));
        writer.flush();
    }

    private static int bfs() {
        LinkedList<int[]> queue = new LinkedList<>();
        //寻找起点
        int x = 0, y = 0, answer = 0;
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                if (graph[i][j] == 'K') {
                    x = i;
                    y = j;
                }
                dis[i][j] = -1;
            }
        }
        dis[x][y] = 0;
        queue.addLast(new int[]{x, y});
        while (!queue.isEmpty()) {
            int[] curr = queue.pollFirst();
            int currX = curr[0], currY = curr[1];
            for (int[] dir : dirs) {
                int nextX = dir[0] + currX, nextY = dir[1] + currY;
                if (nextX < 0 || nextX >= R || nextY < 0 || nextY >= C) continue;
                if (graph[nextX][nextY] == '*' || dis[nextX][nextY] != -1) continue;
                if (graph[nextX][nextY] == 'H') return dis[currX][currY] + 1;
                queue.addLast(new int[]{nextX, nextY});
                dis[nextX][nextY] = dis[currX][currY] + 1;
            }
        }
        return answer;
    }
}
